// pages/messageChat/messageChat.js
const app = getApp()

// import TIM from '../../utils/im/tim-wx';
// import COS from '../../utils/im/cos-wx-sdk-v5';
// let options = {
//   SDKAppID: 1400411226 // 接入时需要将0替换为您的即时通信应用的 SDKAppID
// };
// let tim = TIM.create(options); // SDK 实例通常用 tim 表示
// // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
// // tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
// tim.setLogLevel(1); // release级别，SDK 输出关键信息，生产环境时建议使用
var tim = app.imInit.tim
var TIM = app.imInit.TIM
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: wx.getStorageSync('userId'),
    other_userId: '', //收消息的id
    value: '', //文本框
    nextReqMessageID: '', // 用于续拉，分页续拉时需传入该字段。
    isCompleted: true, // 表示是否已经拉完所有消息。
    messageList: [], //消息列表
    scrollTop: '',
  },
  // 同意提前结束
  clientOrderEarlyEnd(e) {
    let that = this
    var data = e.currentTarget.dataset.data
    var orderId = data.orderId
    console.log('orderId', orderId);

    var postObj = {
      url: '/manage/client/order/orderStatus',
      method: 'POST',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询该订单状态', res)
      var status = res.data.data.status
      if (status === 5001) {
        console.log('订单可以使用');
        //// 用户同意提前结束订单
        let postObj = {
          url: '/manage/client/order/earlyEnd',
          method: 'PUT',
          data: {
            orderId: orderId,
            token: wx.getStorageSync('token'),
            userId: wx.getStorageSync('userId'),
          }
        }
        app.request.gameRequest(postObj).then(res => {
          console.log('用户同意提前结束订单', res)
          wx.showToast({
            title: '已经提前结束！',
            icon: 'none',
            duration: 2000,
          })
        }).catch(err => {
          wx.showToast({
            title: '提前结束失败！',
            icon: 'none',
            duration: 2000,
          })
        })
      } else {
        console.log('订单不可以用');
        wx.showToast({
          title: '订单已失效！',
          icon: 'none',
          duration: 2000,
        })
      }
    }).catch(err => {})
  },
  //  同意 应邀
  iWantGo(e) {
    let that = this
    console.log(e);
    var data = e.currentTarget.dataset.data //开黑语音
    var orderId = data.orderId
    var postObj = {
      url: '/manage/client/order/orderStatus',
      method: 'POST',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询该订单状态', res)
      var status = res.data.data.status
      if (status === 2001) {
        console.log('订单可以使用');
        that.orderReceivingOrders(orderId, data) //// 陪玩者 同意 接单

      } else {
        console.log('订单不可以用');
        wx.showToast({
          title: '订单已失效！',
          icon: 'none',
          duration: 2000,
        })
      }
    }).catch(err => {})

  },
  // 拒绝  应邀
  iDontWantGo(e) {
    let that = this
    console.log(e);
    var data = e.currentTarget.dataset.data
    var orderId = data.orderId
    var postObj = {
      url: '/manage/client/order/orderStatus',
      method: 'POST',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询该订单状态', res)
      var status = res.data.data.status
      if (status === 2001) {
        console.log('订单可以使用');
        that.orderRefuse(orderId) //// 陪玩者 同意 接单
        // wx.showToast({
        //   title: '订单可用！',
        //   icon: 'none',
        //   duration: 2000,
        //   success: () => {
        //     that.orderRefuse(orderId) //// 陪玩者 同意 接单
        //   }
        // })
      } else {
        console.log('订单不可以用');
        wx.showToast({
          title: '订单已失效！',
          icon: 'none',
          duration: 2000,
        })
      }
    }).catch(err => {})
  },
  // 陪玩者 同意 接单
  orderReceivingOrders(orderId, data) {
    let that = this
    var postObj = {
      url: '/manage/client/order/receivingOrders',
      method: 'PUT',
      data: {
        orderId: orderId
      }
    }




    app.request.gameRequest(postObj).then(res => {
      console.log('陪玩者 同意 接单', res)
      wx.showToast({
        title: '应邀成功!',
        icon: 'none',
        duration: 2000,
        success: () => {
          // imgUrl: "https://ywpd-picture.obs.cn-east-2.myhuaweicloud.com:443/photo/838804127-1_photo.png?AccessKeyId=TEPZ5RHAPORK7NWI4AI9&Expires=1697780726&Signature=MxHjVis2VhFWnjr%2FmuWJ41DP6vU%3D"
          // pushUrl: "rtmp://pili-publish.52yuze.com/ywpd/1603704335029"
          // creatTime: "2020-10-26 17:25:35"
          // orderId: 91
          // pullUrl1: "rtmp://pili-live-rtmp.52yuze.com/ywpd/1603704335030"
          // pushUrl1: "rtmp://pili-publish.52yuze.com/ywpd/1603704335030"
          // roomId: 1603704335029
          // roomName: "开黑语音"
          // pullUrl: "rtmp://pili-live-rtmp.52yuze.com/ywpd/1603704335029"



          wx.setStorageSync('voice', data)

          wx.navigateTo({
            url: `/pages/room/room?from=2`,
          })
        }
      })
    }).catch(err => {
      wx.showToast({
        title: '应邀失败!',
        icon: 'none',
        duration: 2000,
      })
    })
  },
  // 陪玩者 拒绝 接单
  orderRefuse(orderId) {
    let that = this
    var postObj = {
      url: '/manage/client/order/refuse',
      method: 'PUT',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      // console.log('陪玩者 拒绝 接单', res)
      wx.showToast({
        title: '拒绝成功!',
        icon: 'none',
        duration: 2000,
      })
    }).catch(err => {
      wx.showToast({
        title: '拒绝失败!',
        icon: 'none',
        duration: 2000,
      })
    })
  },
  // 查询该订单状态
  getOrderStatus(orderId) {
    let that = this
    var postObj = {
      url: '/manage/client/order/orderStatus',
      method: 'post',
      data: {
        orderId: orderId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询该订单状态', res)
      var status = res.data.data.status
      if (status === 2001) {
        // 订单可以使用
        console.log('订单可以使用');
        that.setData({
          status: status
        })
      } else {
        // 订单不可以用
        console.log('订单不可以用');
        that.setData({
          status: status
        })
      }
    }).catch(err => {})
  },
  // 内容change
  onChangevalue(event) {
    // event.detail 为当前输入的值
    this.setData({
      value: event.detail
    })
  },
  // 发送消息
  sendValue() {
    let that = this
    var userId = this.data.other_userId
    var value = this.data.value
    // app.imInit.createTextMessage(userId, value)

    // 发送文本消息，Web 端与小程序端相同
    // 1. 创建消息实例，接口返回的实例可以上屏
    let message = tim.createTextMessage({
      to: userId,
      conversationType: TIM.TYPES.CONV_C2C,
      // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
      // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
      // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
      payload: {
        text: value
      }
    });
    // 2. 发送消息
    let promise = tim.sendMessage(message);
    promise.then(function (imResponse) {
      // 发送成功
      console.log('发送成功', imResponse);
      var message = imResponse.data.message
      var messageList = that.data.messageList
      messageList.push(message)
      that.setData({
        value: '',
        messageList: messageList
      })
      // 到底部去
      let query = wx.createSelectorQuery();
      query.select('.content').boundingClientRect(rect => {
        let clientHeight = rect.height;
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        // console.log(height);
        that.setData({
          scrollTop: height + 100 + 'rpx'
        })
      }).exec();

    }).catch(function (imError) {
      // 发送失败
      console.warn('发送失败sendMessage error:', imError);
    });
  },
  // 
  getMessageListFirst(userId) {
    let that = this
    // 打开某个会话时，第一次拉取消息列表
    let promise = tim.getMessageList({
      conversationID: `C2C${userId}`,
      count: 15
    });
    promise.then(function (imResponse) {
      const messageList = that.jsonParse(imResponse.data.messageList); // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log('，第一次拉取消息列表MessageList', imResponse)



      that.setData({
        nextReqMessageID: nextReqMessageID,
        isCompleted: isCompleted,
        messageList: messageList
      })
    });

  },
  getMessageListLast(userId, nextReqMessageID) {
    let that = this
    // 下拉查看更多消息
    let promise = tim.getMessageList({
      conversationID: `C2C${userId}`,
      nextReqMessageID,
      count: 15
    });
    promise.then(function (imResponse) {
      const messageList = that.jsonParse(imResponse.data.messageList) // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log('查看更多消息MessageList', imResponse)
      var listAll = [...messageList, ...that.data.messageList]

      that.setData({
        nextReqMessageID: nextReqMessageID,
        isCompleted: isCompleted,
        messageList: listAll
      })
    });


  },
  // 监听新消息
  watchMessage() {
    let that = this
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
      // console.log(event)
      var list = that.jsonParse(event.data)
      var message = list[0]
      var messageList = that.data.messageList
      messageList.push(message)

      that.setData({
        messageList: messageList,
      })


      let pages = getCurrentPages();
      let currPage = null;
      // console.log(pages) 的到一个数组
      if (pages.length) {
        // 获取当前页面的对象（上边所获得的数组中最后一项就是当前页面的对象）
        currPage = pages[pages.length - 1];
      }
      // 获取当前页面的路由
      let route = currPage.route
      // console.log('获取当前页面的路由', route)

      if (route == 'pages/messageChat/messageChat') {
        app.imInit.setMessageRead(event.data[0].conversationID)
        // 到底部去
        let query = wx.createSelectorQuery();
        query.select('.content').boundingClientRect(rect => {
          let clientHeight = rect.height;
          let clientWidth = rect.width;
          let ratio = 750 / clientWidth;
          let height = clientHeight * ratio;
          // console.log(height);
          that.setData({
            scrollTop: height + 100 + 'rpx'
          })
        }).exec();
      }



    });
  },
  //滚动
  upper(e) {
    let that = this
    wx.showLoading({
      title: '加载中...'
    })
    // console.log(e)
    var isCompleted = that.data.isCompleted
    if (isCompleted == false) {
      //有更多信息
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {
            that.getMessageListLast(that.data.userId, that.data.nextReqMessageID)
          },
        })
      }, 500)

    } else if (isCompleted == true) {
      //没有更多信息
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '暂无更多消息',
              icon: "none",
              duration: 500
            })
          },
        })
      }, 500)
    }
  },
  lower(e) {
    // console.log(e)
  },
  // jsonParse   extension: "{"code":1,"desc":"您已被请在10秒内接受否则订单取消！"}"
  //根据 payload 消息转换成json对象
  jsonParse(e) {
    if (e instanceof Object) {
      if (e.type == "TIMTextElem") {
        return e
      }
      if (e.type == "TIMCustomElem") {
        e.payload.extension = JSON.parse(e.payload.extension)
        return e
      }
    }
    if (e instanceof Array) {
      e.forEach((items, i) => {
        if (items.type == "TIMCustomElem") {
          if (items.payload.extension instanceof Object) {} else {
            items.payload.extension = JSON.parse(items.payload.extension)
          }
        }
      })
      console.log(e)
      return e
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var other_userId = options.userId.toString()
    that.setData({
      other_userId: other_userId
    })


    that.watchMessage()
    that.getMessageListFirst(other_userId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // app.imInit.onMessageReceived(tim, TIM)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // app.imInit.onMessageReceived(tim, TIM)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})